using System.Linq;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Migrations;
using YZAutoDWR.Entity;

namespace YZAutoDWR.Data;

public class DWRDbContext : DbContext
{
    private const string ConnectionString = "Data Source=UserConfig.db";
    public DbSet<UserConfigEntity> UserConfig { get; set; }
    public DbSet<WorkOrderEntity> WorkOrder { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseSqlite(ConnectionString,
                sqliteOptions => sqliteOptions
                    .MigrationsAssembly(typeof(DWRDbContext).Assembly.FullName)
                    .CommandTimeout(30))
            .ReplaceService<IMigrationsIdGenerator, MigrationsIdGenerator>();
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // 加载配置类
        modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
    }
}

public class UserConfigConfiguration : IEntityTypeConfiguration<UserConfigEntity>
{
    public void Configure(EntityTypeBuilder<UserConfigEntity> builder)
    {
        // 主键配置
        builder.HasKey(x => x.Id);
        builder.Property(x => x.Id)
            .ValueGeneratedNever()
            .HasDefaultValue(1); // 固定ID

        // 布尔值默认配置
        builder.ConfigureBoolDefaults();

        // 字段配置
        /*builder.Property(x => x.PlatformUrl)
            .HasMaxLength(256)
            .HasDefaultValue("www.baidu.com");*/
    }
}

public static class EntityConfigurationExtensions
{
    public static void ConfigureBoolDefaults(this EntityTypeBuilder builder)
    {
        foreach (var property in builder.Metadata.ClrType
                     .GetProperties()
                     .Where(p => p.PropertyType == typeof(bool)))
        {
            builder.Property(property.Name)
                .HasDefaultValue(false);
        }
    }
}